package com.fuhao.pay.callback.template.CallbackTemplate;

import com.fuhao.pay.callback.template.AbstractPayCallbackTemplate;
import com.fuhao.pay.constant.PayConstant;
import com.fuhao.pay.entity.PaymentTransactionEntity;
import com.fuhao.pay.mapper.PaymentTransactionMapper;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.unionpay.acp.sdk.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhang
 * @title: 微信扫码回调
 */
@Component
public class WxPayCallbackTemplate extends AbstractPayCallbackTemplate {

    @Autowired
    private WXPay wxPay;
    @Autowired
    private PaymentTransactionMapper paymentTransactionMapper;

    @Override
    public Map<String, String> verifySignature(HttpServletRequest req, HttpServletResponse resp, Map<String, String> params) {
        try {
            boolean signatureValid = wxPay.isPayResultNotifySignatureValid(params);
            if(signatureValid){
                // 【注：为了安全验签成功才应该写商户的成功处理逻辑】交易成功，更新商户订单状态
                String orderId = params.get("out_trade_no"); // 获取后台通知的数据，其他字段也可用类似方式获取
                params.put("paymentId", orderId);
                params.put(PayConstant.RESULT_NAME, PayConstant.RESULT_PAYCODE_200);
            }else {
                LogUtil.writeLog("银联验证签名结果[失败].");
                params.put(PayConstant.RESULT_NAME, PayConstant.RESULT_PAYCODE_201);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return params;
    }

    @Override
    public String asyncService(Map<String, String> verifySignature) throws Exception {
        String returnCode = verifySignature.get("return_code");
        String resultCode = verifySignature.get("result_code");
        String orderId = verifySignature.get("out_trade_no");
        if(!("SUCCESS".equals(returnCode) && "SUCCESS".equals(resultCode))){
            return failResult();
        }
        // 根据日志 手动补偿 使用支付id调用第三方支付接口查询
        PaymentTransactionEntity paymentTransaction = paymentTransactionMapper.selectByPaymentId(orderId);
        if (paymentTransaction.getPaymentStatus() == PayConstant.PAY_STATUS_SUCCESS) {
            // 网络重试中，之前已经支付过
            return successResult();
        }
        // 2.将状态改为已经支付成功
        paymentTransactionMapper.updatePaymentStatus(PayConstant.PAY_STATUS_SUCCESS, orderId,PayConstant.WX_CHANNEL);
        // 3.调用积分服务接口增加积分(处理幂等性问题)
        return successResult();
    }

    @Override
    public String failResult() throws Exception {
        Map<String, String> responseMap = new HashMap<>(2);
        responseMap.put("return_code", "failed");
        responseMap.put("return_msg", "no");
        String responseXml = WXPayUtil.mapToXml(responseMap);
        return responseXml;
    }

    @Override
    public String successResult() throws Exception {
        Map<String, String> responseMap = new HashMap<>(2);
        responseMap.put("return_code", "SUCCESS");
        responseMap.put("return_msg", "OK");
        String responseXml = WXPayUtil.mapToXml(responseMap);
        return responseXml;
    }
}
